﻿@page "/Chat/{Id?}"
@page "/"
@inject NavigationManager Navigation
@using System.Net.Http.Headers
@using LiveHub.DataModels
@using Microsoft.AspNetCore.SignalR.Client
@implements IAsyncDisposable
@inject HttpClient HttpClient

<PageTitle>聊天 - LiveHub</PageTitle>

@if (string.IsNullOrEmpty(Jwt))
{
    <Login/>
}
else
{
    <GridRow OnBreakpoint="OnBreakpoint" Style="height: 100%;">
        <GridCol Xs="24" Sm="24" Md="4" Lg="4" Xl="4" Xxl="4" Style="height: 100%">
            <Flex Class="phone-desktop-flex" Style="height: 10%;">
                <Image Style="width:40px; height:40px" Preview="false" Src="@(Member.Gender == "男" ? "_content/LiveHub.WebUI/Centre/男生.png" : "_content/LiveHub.WebUI/Centre/女生.png")"/>
            </Flex>
            <a href="/" class="desktop-phone-flex" style="height: 10%;">
                <Flex Gap="large">
                    <Image Src="_content/LiveHub.WebUI/iOS_Club_LOGO.png" Preview="false" Style="width:40px; height:40px"/>
                    <div style="font-size: 24px;font-weight: bold;color: #1c1f23" Class="desktop-phone-flex">LiveHub</div>
                </Flex>
            </a>
            <Menu Mode="@MenuMode.Inline">
                @foreach (var item in Member.Groups)
                {
                    <MenuItem RouterLink="@($"/Chat/{item.GroupId}")" RouterMatch="NavLinkMatch.All">@item.Name</MenuItem>
                }
            </Menu>
        </GridCol>
        <GridCol Span="@(!(IsMobile && string.IsNullOrEmpty(Id)) ? 20 : 0)" Style="height: 100%;overflow: hidden">
            <div Style="height: 10%;background-color: #ffffff">
                <Flex Justify="space-between" Gap="16" Style="margin: 5px;">
                    <Text style="font-size: 24px;font-weight: bold;color: #1c1f23">@Group.Name</Text>
                    <Text style="font-size: 24px;font-weight: bold;color: #1c1f23">@Group.Users.Count</Text>
                </Flex>
            </div>
            <div Style="height: 75%;padding: 20px;overflow: auto;">
                @foreach (var message in Messages)
                {
                    @if (message.UserId == Member.UserId)
                    {
                        <Flex Justify="flex-end" Gap="16" Style="margin: 5px;">
                            <Flex Justify="space-between" Align="flex-end" Vertical>
                                <Text>@message.User.UserName</Text>
                                <Text style="background-color: #7CFC00;padding: 10px;" class="chat">@message.Body</Text>
                            </Flex>
                            <Avatar Style="background-color: #f56a00">@message.User.UserName.First()</Avatar>
                        </Flex>
                    }
                    else
                    {
                        <Flex Gap="16" Style="margin: 5px;">
                            <Avatar Style="background-color: #7265e6">@message.User.UserName.First()</Avatar>
                            <Flex Justify="flex-end" Vertical>
                                <Text>@message.User.UserName</Text>
                                <Text style="background-color: #f3f5f7;padding: 10px;" class="chat">@message.Body</Text>
                            </Flex>
                        </Flex>
                    }
                }
            </div>
            <div Style="height: 15%">
                <Flex Justify="flex-end">
                    <Button Type="@ButtonType.Primary" @onclick="Send" disabled="@(!IsConnected)">Send</Button>
                </Flex>
                <TextArea @bind-Value="@Input" Placeholder="请输入消息"></TextArea>
            </div>
        </GridCol>
    </GridRow>
}

@code {
    [Parameter] public string? Id { get; set; }
    [CascadingParameter(Name = "Jwt")] private string Jwt { get; set; } = "";
    [CascadingParameter(Name = "Member")] private UserModel Member { get; set; } = new();
    private HubConnection? hubConnection;
    private List<MessageModel> Messages { get; set; } = [];
    private GroupModel Group { get; set; } = new();
    private string Input { get; set; } = "";

    protected override async Task OnInitializedAsync()
    {
        hubConnection = new HubConnectionBuilder()
            //.WithUrl(Navigation.ToAbsoluteUri($"{ModelData.ChatApiUrl}/LiveChat"))
            .Build();

        hubConnection.On<MessageModel>("ReceiveMessage", message =>
        {
            Messages.Add(message);
            InvokeAsync(StateHasChanged);
        });

        await hubConnection.StartAsync();
    }

    protected override async Task OnParametersSetAsync()
    {
        var id = Id ?? "iOS Club";
        HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Jwt);

        var response = await HttpClient.GetAsync($"{ModelData.ChatApiUrl}/api/Group/GetData/{id}");
        if (response.IsSuccessStatusCode)
        {
            var group = await response.Content.ReadFromJsonAsync<GroupModel>();
            if (group is not null)
            {
                Group = group;
                Messages = group.Messages;
            }
        }

        response = await HttpClient.GetAsync($"{ModelData.ChatApiUrl}/api/Group/GetGroups");
        if (response.IsSuccessStatusCode)
        {
            var groups = await response.Content.ReadFromJsonAsync<List<GroupModel>>();
            if (groups is not null)
            {
                Member.Groups = groups;
            }
        }
    }

    private async Task Send()
    {
        if (hubConnection is not null && !string.IsNullOrEmpty(Input))
        {
            var id = Id ?? "iOS Club";
            await hubConnection.SendAsync("SendMessage", id,
                new MessageModel() { Body = Input, UserId = Member.UserId, User = Member });
            Input = "";
        }
    }

    private bool IsConnected =>
        hubConnection?.State == HubConnectionState.Connected;

    public async ValueTask DisposeAsync()
    {
        if (hubConnection is not null)
        {
            await hubConnection.DisposeAsync();
        }
    }

    private void OnBreakpoint(BreakpointType breakpoint)
    {
        IsMobile = (int)breakpoint <= 800;
    }

    private bool IsMobile;

}

<style>
    .chat{
        max-width: 50vw;
        padding: 10px;
        border-radius: 10px;
    }
</style>